package com.zlyx.easy.api.config;

import java.io.File;
import java.io.FileReader;
import java.text.MessageFormat;
import java.util.List;

import org.apache.maven.model.Developer;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.zlyx.easy.api.extension.ApiReaderExtension;
import com.zlyx.easy.api.extension.ReaderExtension;
import com.zlyx.easy.core.collections.Lists;
import com.zlyx.easy.core.tool.StringFormat;

import io.swagger.models.Contact;
import io.swagger.models.Info;
import io.swagger.models.Swagger;

/**
 * Api配置
 * 
 * @Auth 赵光
 * @Describle
 */
@Configuration
public class ApiConfig {

	@Bean
	@ConditionalOnMissingBean
	public ReaderExtension ApiReaderExtension() {
		return new ApiReaderExtension();
	}

	private static String mavenDependency = "&lt;dependency&gt;<br/>"
			+ "&nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;{0}&lt;/groupId&gt;<br/>"
			+ "&nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;{1}&lt;/artifactId&gt;<br/>"
			+ "&nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;{2}&lt;/version&gt;<br/>" + "&lt;/dependency&gt;<br/>";

	public static Swagger getSwagger() {
		Swagger swagger = new Swagger();
		Info info = swagger.getInfo();
		if (info == null) {
			info = new Info();
			swagger.setInfo(info);
		}
		try {
			MavenXpp3Reader reader = new MavenXpp3Reader();
			String myPom = System.getProperty("user.dir") + File.separator + "pom.xml";
			if (new File(myPom).exists()) {
				Model model = reader.read(new FileReader(myPom));
				info.setTitle(model.getArtifactId());
				info.setDescription(MessageFormat.format(mavenDependency, model.getGroupId(), model.getArtifactId(),
						model.getVersion()));
				info.setVersion(model.getVersion());
				info.setTermsOfService(model.getUrl());
				List<String> developers = Lists.newList();
				List<String> emails = Lists.newList();
				List<String> urls = Lists.newList();
				if (!model.getDevelopers().isEmpty()) {
					List<Developer> developerList = model.getDevelopers();
					for (Developer developer : developerList) {
						developers.add(developer.getName());
						emails.add(developer.getEmail());
						urls.add(developer.getUrl());
					}
				}
				Contact contact = new Contact().name(StringFormat.format(developers, ", "))
						.email(StringFormat.format(emails, ", ")).url(StringFormat.format(urls, ", "));
				info.setContact(contact);
			}
		} catch (Exception e) {

		}
		return swagger;
	}
}
